<?php
/**
 * (logic) 获取乐天平台订单
 * User: bgl
 * Date: 2022/9/21
 * Time: 10:55
 */

namespace App\Logic\Plat\Rakuten;

use App\Libs\Rakuten\Common\RakutenClient;
use App\Logic\Amazon\Api\CustomerOutbound;
use App\Logic\Amazon\Api\CustomerOutBoundWork;
use App\Logic\Amazon\Api\RequiredConfig;
use App\Logic\Plat\Rakuten\Overseas\GuCang\Order\OverseasOrder;
use App\Models\Amazon\FBAMYIInventory;
use App\Models\Basics\AmazonAccount;
use App\Models\Basics\ExpressCompany;
use App\Models\Basics\SysArea;
use App\Models\Basics\SysCountry;
use App\Models\Basics\SysPlat;
use App\Models\Basics\SysPlatCountry;
use App\Models\CustomerDelivery\CustomerDelivery;
use App\Models\CustomerDelivery\CustomerDeliveryDetail;
use App\Models\CustomerDelivery\CustomerOrder;
use App\Models\OverSeasBa\DropshippingInventoryFnsku;
use App\Models\Product\ProductRakutenSku;
use App\Models\Product\ProductSku;
use App\Models\Rakuten\RakutenLogs;
use App\Models\Rakuten\RakutenOrder;
use App\Models\Rakuten\RakutenOrderCondition;
use App\Models\Rakuten\RakutenOrderItem;
use App\Models\SalesReport\FBAInventory;
use Illuminate\Support\Facades\DB;

class GrabOrders{

    const GRAB_ORDERS_INTERVAL = 3600 * 24 * 30 * 12; //一年

    const ORDER_SEARCH_ORDER = 'es/2.0/order/searchOrder/'; //查询订单列表
    const ORDER_GET_ORDER = 'es/2.0/order/getOrder/'; //获取订单
    const ORDER_UPDATE_ORDER_SHIPPING = 'es/2.0/order/updateOrderShipping/'; //订单发货
    const INVENTORY_BULK_UPSERT = 'es/2.1/inventories/bulk-upsert/'; //同步库存
    const AREA_JP = SysArea::AREA_JP; //JP站点ID

    /**
     * 获取rakuten平台订单
     * rakuten
     * @return string
     */
    public static function getRakutenOrder(){

        //dd('rakuten-API!');
        //date_default_timezone_set('Asia/Tokyo'); //日本东京时间

        //获取本次开始时间 (上次最后执行时间)
        $beforeStartTime = RakutenOrderCondition::getNextStartTime();
        if(!$beforeStartTime) return null;

        //组装api参数,转换时间格式 (日本时区)
        $afterStartTime = $beforeStartTime + self::GRAB_ORDERS_INTERVAL;
        if($afterStartTime > time()) $afterStartTime = time();
        $apiParams['startDatetime'] = getDateFormat(date('Y-m-d H:i:s', $beforeStartTime - 600), 'JST', 'Y-m-d\TH:i:sO');  //本次开始时间
        $apiParams['endDatetime'] = getDateFormat(date('Y-m-d H:i:s', $afterStartTime), 'JST', 'Y-m-d\TH:i:sO'); //本次结束时间(下次开始时间)
        $apiParams['orderProgressList'] = [300]; //订单状态(100:挂单确认, 200:乐天加工, 300:待发货, 400:等待更改确认, 500:已发货, 600:付款正在进行中, 700:付款已处理, 800:等待确认, 900:取消确认)
        $apiParams['dateType'] = 3; //日期类型(3:订单确认日期)
        $apiParams['PaginationRequestModel'] = [
            'requestRecordsAmount' => 100,
            'requestPage' => 1,
            'SortModelList' => [
                [
                    'sortColumn' => 1,
                    'sortDirection' => 1
                ]
            ]
        ];
        $apiUrl = self::ORDER_SEARCH_ORDER; //api方法

        //获取原始订单数据(原始订单号数据)
        $data = RakutenClient::getRequest($apiUrl, $apiParams);

        $totalCount = 0;
        $orderData = [];
        //订单分页数据处理
        if (!empty($data->PaginationResponseModel)) {

            for ($pages = 1; $pages <= $data->PaginationResponseModel->totalPages; $pages++){

                $apiParams['PaginationRequestModel']['requestPage'] = $pages; //循环页码查询(翻页)

                //获取rakuten原始订单号(分页循环)
                $order = RakutenClient::getRequest($apiUrl, $apiParams);

                //创建rakuten订单及明细(循环创建)
                $apiUrlOne = self::ORDER_GET_ORDER; //api方法
                $apiParamsOne['version'] = 7; //版本
                $apiParamsOne['orderNumberList'] = $order->orderNumberList;
                $rakutenOrder = RakutenClient::getRequest($apiUrlOne, $apiParamsOne);
                self::rakutenOrders($rakutenOrder);

                //订单号集合
                $orderData[] = $order->orderNumberList;
            }

            if ($data->PaginationResponseModel->totalRecordsAmount > 0) {
                $totalCount = $data->PaginationResponseModel->totalRecordsAmount;
            }

            //更新最后执行时间 (下次开始时间)
            RakutenOrderCondition::upNextStartTime($afterStartTime);

            //添加运行日志
            RakutenLogs::logs(RakutenLogs::$orderSync, date('Y-m-d H:i:s', $beforeStartTime).',['. $totalCount .']条,rakuten订单同步成功!', $orderData);
        }
    }

    /**
     * 创建rakuten基础订单
     * @param $orders
     */
    public static function rakutenOrders($orders){
        DB::connection('mysql_rakuten')->beginTransaction();
        try {
            if ($orders->OrderModelList) {
                foreach ($orders->OrderModelList as $item) {
                    $orderNo = $item->orderNumber;
                    $rakutenOrder = RakutenOrder::query()->where('order_id', $orderNo)->first();
                    if ($rakutenOrder) continue;

                    //订单
                    $order = [];
                    $order['order_id'] = $orderNo;
                    $order['order_progress'] = $item->orderProgress;
                    $order['order_datetime'] = strtotime($item->orderDatetime);
                    $order['order_type'] = $item->orderType;
                    $order['goods_price'] = $item->goodsPrice ?? 0;
                    $order['total_price'] = $item->totalPrice ?? 0; //订单总金额
                    $order['total_coupon_price'] = $item->couponAllTotalPrice ?? 0; //订单总优惠金额
                    $order['total_point_price'] = $item->PointModel->usedPoint ?? 0; //订单总优惠积分
                    $order['request_price'] = $item->requestPrice ?? 0; //订单实际总金额

                    $orderItem = []; //订单明细
                    $orderAddress = []; //订单地址
                    $orderShipping = []; //订单物流(初始包裹id)
                    $orderShippingDetails = []; //订单物流明细(初始包裹id)
                    foreach ($item->PackageModelList as $key => $value) {

                        //订单物流
                        $basketId = $value->basketId;
                        $orderShipping[$key]['basket_id'] = $basketId;

                        //物流明细
                        $orderShippingDetail = [];
                        if($value->ShippingModelList){
                            foreach ($value->ShippingModelList as $k1 => $v1) {
                                $orderShippingDetail[$k1]['order_id'] = $orderNo;
                                $orderShippingDetail[$k1]['shipping_detail_id'] = $v1->shippingDetailId ?? '';
                                $orderShippingDetail[$k1]['shipping_number'] = $v1->shippingNumber ?? '';
                                $orderShippingDetail[$k1]['delivery_company'] = $v1->deliveryCompany ?? '';
                                $orderShippingDetail[$k1]['delivery_company_name'] = $v1->deliveryCompanyName ?? '';
                                $orderShippingDetail[$k1]['shipping_date'] = $v1->shippingDate ?? '';
                            }
                        }else{
                            $orderShippingDetail[0]['order_id'] = $orderNo;
                        }
                        $orderShippingDetails[$basketId] = $orderShippingDetail;

                        //订单明细
                        if ($value->ItemModelList) {
                            foreach ($value->ItemModelList as $k2 => $v2) {
                                $orderItem[$k2]['item_id'] = $v2->itemId;
                                $orderItem[$k2]['basket_id'] = $basketId;
                                $orderItem[$k2]['item_detail_id'] = $v2->itemDetailId;
                                $orderItem[$k2]['item_name'] = $v2->itemName ?? '';
                                $orderItem[$k2]['manage_number'] = $v2->manageNumber ?? '';
                                $orderItem[$k2]['item_number'] = $v2->itemNumber ?? '';
                                if ($v2->SkuModelList) {
                                    foreach ($v2->SkuModelList as $skuList => $sku){
                                        $pskuId = ProductSku::getValueByCode(trim($sku->variantId), 'id');
                                        $orderItem[$k2]['psku_id'] = $pskuId ?? 0; //erp公司产品ID
                                        $orderItem[$k2]['variant_id'] = trim($sku->variantId) ?? ''; //乐天产品变体ID
                                        $orderItem[$k2]['platform_sku'] = $sku->merchantDefinedSkuId ?? ''; //乐天平台sku
                                    }
                                    $orderItem[$k2]['platform_sku_info'] = json_encode($v2->SkuModelList, JSON_UNESCAPED_UNICODE) ?? ''; //乐天平台sku信息
                                }
                                $orderItem[$k2]['units'] = $v2->units ?? 0;
                                $orderItem[$k2]['price'] = $v2->price ?? 0;
                            }
                        }

                        //订单地址
                        if ($value->SenderModel) {
                            //包裹收件人地址
                            $orderAddress['country'] = 'JP';
                            $orderAddress['country_code'] = 'JP';
                            $orderAddress['family_name'] = $value->SenderModel->familyName . $value->SenderModel->firstName ?? '';
                            $orderAddress['prefecture'] = $value->SenderModel->prefecture ?? '';
                            $orderAddress['city'] = $value->SenderModel->city ?? '';
                            $orderAddress['address'] = $value->SenderModel->subAddress ?? '';
                            $orderAddress['zip_code'] = $value->SenderModel->zipCode1 . $value->SenderModel->zipCode2 ?? '';
                            $orderAddress['email'] = $item->OrdererModel->emailAddress ?? ''; //订购人邮箱
                            $orderAddress['phone_number'] = $value->SenderModel->phoneNumber1 . $value->SenderModel->phoneNumber2 . $value->SenderModel->phoneNumber3 ?? '';
                        }
                    }

                    //创建rakuten订单
                    $rakutenOrder = RakutenOrder::query()->create($order);
                    $rakutenOrder->rakuten_orders_items()->createMany($orderItem);
                    $rakutenOrder->rakuten_orders_address()->create($orderAddress);

                    ////物流
                    //$orderShippingObj = $rakutenOrder->rakuten_orders_shipping()->createMany($orderShipping);
                    //if ($orderShippingObj) {
                    //    foreach ($orderShippingObj as $shipping){
                    //        $shipping->rakuten_orders_shipping_details()->createMany($orderShippingDetails[$shipping->basket_id]);
                    //    }
                    //}
                }

                DB::connection('mysql_rakuten')->commit();
            }
        }catch (\Exception $e){
            DB::connection('mysql_rakuten')->rollBack();
            report($e);
        }
    }

    /**
     * 将未同步的rakuten订单同步至ERP
     * rakuten订单同步至消费者订单表
     * @param array $orderIds = []
     * @param bool $isOpenStock
     */
    public static function syncRakutenOrder($orderIds = [],$isOpenStock = true){

        //rakuten未同步订单
        $query = RakutenOrder::query();
        $query->where('erp_sync', RakutenOrder::SYNC_NO);
        if(!empty($orderIds)){
            $query->whereIn('order_id', $orderIds);
        }
        $rakutenOrders = $query->orderBy('id')->get();
        if (!$rakutenOrders) dd('over!');

        foreach($rakutenOrders as $rakutenOrder){
            if (!$rakutenOrder) continue;
            $orderNo = $rakutenOrder->order_id;

            //验证Rakuten产品类型(乐天订单)
            $isOsWarehouseSkuFlag = false;
            if ($rakutenOrder->rakuten_orders_items) {
                foreach ($rakutenOrder->rakuten_orders_items as $_k => $_v) {
                    $isOsWarehouse = ProductRakutenSku::getValueByCode($_v->platform_sku, 'is_os_warehouse');  //是否为海外仓产品(1:是 2:否)
                    if ($isOsWarehouse) {
                        if ($isOsWarehouse == ProductRakutenSku::OS_WAREHOUSE_NO){
                            $isOsWarehouseSkuFlag = false; //非海外仓产品
                            break;
                        }
                        $isOsWarehouseSkuFlag = true; //海外仓产品
                    }
                }
            }

            /****乐天订单同步至海外仓(谷仓)****/
            //一：海外仓产品 (海外仓库存(海外仓订单)(海外仓发货))
            if ($isOsWarehouseSkuFlag == true) {
                $dropshippingInventoryFlag = DropshippingInventoryFnsku::_checkDropshippingInventoryFnsku($rakutenOrder);
                if ($dropshippingInventoryFlag == true) {
                    //创建erp客户订单
                    $customerOrderFlag = CustomerOrder::addRakutenCustomerOrder([$rakutenOrder]);
                    if (!$customerOrderFlag) continue;
                    sleep(1);

                    //创建erp客户发货单(海外仓发货)
                    $customerDeliveryFlag = CustomerOrder::addCustomerDelivery($rakutenOrder,CustomerDelivery::DELIVERY_TYPE_ABROAD,200000);
                    if (!$customerDeliveryFlag) continue;
                    sleep(1);

                    //更新,扣减JP-海外代发库存
                    if ($isOpenStock == true) {
                        DropshippingInventoryFnsku::_saveDropshippingInventoryFnsku($rakutenOrder);
                    }
                }else{
                    //海外仓库存不满足,创建erp客户订单(未选择发货方式的初始订单)(未发货订单)
                    CustomerOrder::addRakutenCustomerOrder([$rakutenOrder]);
                }
            }else{
                //海外仓库存不满足,创建erp客户订单(未选择发货方式的初始订单)(未发货订单)
                CustomerOrder::addRakutenCustomerOrder([$rakutenOrder]);
            }
            /****乐天订单同步至海外仓(谷仓)****/

            /*//二：非海外仓产品((FBA、国内订单)(FBA、国内发货))
            if ($isOsWarehouseSkuFlag == false) {
                //验证：FBA库存(非海外仓订单)(FBA发货)
                list($fbaInventoryFlag,$accountId) = FBAInventory::_checkJpFbaInventoryFnsku($rakutenOrder);
                if ($fbaInventoryFlag == true) {
                    //创建erp客户订单
                    $customerOrderFlag = CustomerOrder::addRakutenCustomerOrder([$rakutenOrder]);
                    if (!$customerOrderFlag) continue;
                    sleep(1);

                    //创建erp客户发货单(FBA发货)
                    $customerDeliveryFlag = CustomerOrder::addCustomerDelivery($rakutenOrder,CustomerDelivery::DELIVERY_TYPE_FBA,$accountId);
                    if (!$customerDeliveryFlag) continue;
                    sleep(1);

                    //更新JP-FBA库存
                    if ($isOpenStock == true) {
                        FBAInventory::_saveJpFbaInventoryFnsku($rakutenOrder);
                    }
                }else{
                    //海外仓库存不满足,创建erp客户订单(未选择发货方式的初始订单)(未发货订单)
                    CustomerOrder::addRakutenCustomerOrder([$rakutenOrder]);
                }
            }*/

            ////三：(非海外仓订单)(国内发货)
            ////验证：国内库存
            //$cnInventoryFlag = AreaCn::_checkCnInventoryFnsku($rakutenOrder);
            //if ($cnInventoryFlag == true) {
            //    //创建erp相关客户订单(国内发货)
            //    RakutenOrder::addRakutenCustomerOrder([$rakutenOrder], CustomerDelivery::DELIVERY_TYPE_CN);
            //
            //    //更新JP-国内库存
            //    if ($isOpenStock == true) {
            //        AreaCn::_saveCnInventoryFnsku($rakutenOrder);
            //    }
            //    continue;
            //}
        }
    }

    /**
     * 乐天异常订单同步 (消费者异常订单)
     * @param array $orderIds
     */
    public static function syncRakutenOrderException($orderIds = []){

        $platId = SysPlat::PLAT_RAKUTEN;
        DB::beginTransaction();
        try{

            //rakuten异常订单
            $query = RakutenOrder::query()->where('erp_sync', RakutenOrder::SYNC_ERROR);
            if(!empty($orderIds)){
                $query->whereIn('order_id',$orderIds);
            }
            $rakutenOrderException = $query->orderBy('id')->get();

            $logData = [];
            $i = 0;
            //订单同步
            if ($rakutenOrderException) {
                $countryCode = 'JP'; //国家编码
                $countryId = SysPlatCountry::getCountryId($countryCode); //国家id
                $areaId = SysPlatCountry::getAreaIdByCountryId($countryId); //站点id

                foreach($rakutenOrderException as $order){
                    $orderNo = $order->order_id;
                    $count = CustomerOrder::query()->where('order_no', $orderNo)->count();
                    if($count > 0){
                        $order->erp_sync = RakutenOrder::SYNC_YES; //已同步
                        $order->save();
                        continue;
                    }

                    //订单
                    $customerOrder = [
                        'order_no'      => $orderNo,
                        'order_at'      => date('Y-m-d H:i:s', $order->order_datetime), //下单时间
                        'order_channel' => CustomerOrder::ORDER_CHANNEL_CUSTOMER, //订单渠道 (1.C端，2.B端)
                        'order_type'    => CustomerOrder::ORDER_TYPE_NORMAL, //订单类型 (1.普通订单，2.寄样订单)
                        'plat_id'       => $platId, //订单平台 (0:无 1:FBA亚马逊 2:shopify 3:乐天)
                        'area_id'       => $areaId, //站点id
                        'country_id'    => $countryId, //国家id
                        'country_code'  => $countryCode, //国家编码
                    ];

                    //订单明细
                    $customerOrderDetail = [];
                    $itemFlag = false;
                    $skuArr = [];
                    foreach($order->rakuten_orders_items as $item){

                        //(唯一)验证订单同一sku是否存在多个
                        $key = $orderNo.'_'.$item->platform_sku;
                        if(in_array($key,$skuArr)){
                            continue;
                        }else{
                            $skuArr[] = $key;
                        }

                        $goodsCode = ProductRakutenSku::getValueByCode($item->platform_sku, 'psku_id'); //通过平台SKU匹配公司产品(psku_id)
                        if(!$goodsCode) {
                            if(!$itemFlag){
                                $itemFlag = true;
                            }
                            if($item->erp_sync != RakutenOrder::SYNC_ERROR){
                                $item->erp_sync = RakutenOrder::SYNC_ERROR; //异常：匹配失败
                                $item->save();
                            }
                            continue;
                        }
                        if($item->erp_sync != RakutenOrder::SYNC_YES){
                            $item->erp_sync = RakutenOrder::SYNC_YES;//同步正常
                            $item->save();
                        }
                        $customerOrderDetail[] = [
                            'plat_id'   => $platId, //订单平台 (0:无 1:FBA亚马逊 2:shopify 3:乐天)
                            'plat_sku'  => $item->platform_sku,
                            'psku_id'   => $goodsCode,
                            'order_num' => $item->units,
                            'apply_num' => 0,
                        ];
                    }
                    if($itemFlag){
                        continue;
                    }
                    if(count($customerOrderDetail) != count($order->rakuten_orders_items)){
                        continue;
                    }
                    //当多个sku相同时,合并累加相同sku的下单数量
                    $orderDetail = [];
                    foreach ($customerOrderDetail as $k => $v){
                        if (!isset($orderDetail[$v['plat_sku']])){
                            $orderDetail[$v['plat_sku']]= $v ;
                        } else {
                            $orderDetail[$v['plat_sku']]['units'] += $v['units'];
                        }
                    }

                    //订单地址
                    $customerOrderReceiver = [
                        'country'   => $order->rakuten_orders_address->country ?? '',
                        'receiver'  => $order->rakuten_orders_address->family_name ?? '',
                        'state'     => $order->rakuten_orders_address->prefecture ?? '',
                        'city'      => $order->rakuten_orders_address->city ?? '',
                        'address'   => $order->rakuten_orders_address->address ?? '',
                        'postcode'  => $order->rakuten_orders_address->zip_code ?? '',
                        'phone'     => $order->rakuten_orders_address->phone_number ?? '',
                    ];

                    //创建消费订单
                    $customerOrderObj = CustomerOrder::query()->create($customerOrder);
                    $customerOrderObj->detail()->createMany($orderDetail);
                    $customerOrderObj->receiver()->create($customerOrderReceiver);

                    //更新乐天订单
                    $order->erp_sync = RakutenOrder::SYNC_YES;//同步正常
                    $order->save();

                    $logData[] = $orderNo;
                    $i++;

                    DB::commit();
                }

                //添加日志
                $totalCount = $i;
                RakutenLogs::logs(RakutenLogs::$customerOrderException, date('Y-m-d H:i:s', time()).',['. $totalCount .']条,消费者异常订单同步成功!', $logData);
            }

        }catch (\Exception $e){
            DB::rollBack();
            report($e);
        }
    }

    /**
     * （向rakuten平台回写订单物流数据）
     * 同步乐天订单的物流追踪号
     * @return null
     */
    public static function syncRakutenOrderTrackingNo(){

        //rakuten乐天物流公司
        $rakutenCompany = ExpressCompany::options(['platform_type' => SysPlat::PLAT_RAKUTEN], 'name_en', 'code')->toArray();
        if (!$rakutenCompany) die('not logistics!!!');

        while(true) {
            //乐天平台物流未同步的发货单
            $delivery = CustomerDeliveryDetail::query()
                ->where('plat_id', SysPlat::PLAT_RAKUTEN) //乐天平台
                ->where('status', '<=', 5) //发货状态
                ->where('sync_status', CustomerDeliveryDetail::SYNC_STATUS_YES) //1：平台物流已同步
                ->where('is_sync_rakuten', 0)  //0：乐天物流未同步
                ->where('created_at', '>=', '2024-11-01 00:00:00')
                ->first();
            if (!$delivery) break;

            //乐天订单下的发货包裹id
            $orderNo = $delivery->order_no;
            $basketId = RakutenOrderItem::query()->where('order_id',$orderNo)->value('basket_id');
            if (!$basketId) break;

            $params = [];
            $basketidModelList = [];
            if ($delivery->shipping_detail_id) $params['shippingDetailId'] = $delivery->shipping_detail_id; //乐天发货明细id
            if ($delivery->tracking_no) $params['shippingNumber'] = $delivery->tracking_no; //乐天物流公司追踪号
            //乐天物流公司编码
            if ($delivery->delivery_company) {
                $params['deliveryCompany'] = $delivery->delivery_company;
            }else{
                $params['deliveryCompany'] = self::getRakutenCompanyCode($rakutenCompany, $delivery->logistics_type);
            }
            //乐天物流公司发货日期
            if ($delivery->delivered_at){
                $params['shippingDate'] = date('Y-m-d', strtotime($delivery->delivered_at));
            }else{
                $params['shippingDate'] = date('Y-m-d', time());
            }

            $basketidModelList[0]['basketId'] = $basketId;
            $basketidModelList[0]['ShippingModelList'][] = $params;
            $apiUrl = self::ORDER_UPDATE_ORDER_SHIPPING; //api方法(订单发货)
            $apiParams = [
                'orderNumber' => $orderNo,
                'BasketidModelList' => $basketidModelList
            ];

            //erp订单物流回传至Rakuten平台
            $result = RakutenClient::getRequest($apiUrl, $apiParams);
            if ($result) {
                if ($result->MessageModelList) {
                    foreach ($result->MessageModelList as $k => $v){
                        //更新订单物流信息
                        $delivery->delivery_company = $params['deliveryCompany']; //rakuten物流公司编码
                        $delivery->shipping_date = $params['shippingDate']; //rakuten物流配送时间
                        $delivery->shipping_detail_id = $v->shippingDetailId; //rakuten物流发货明细id
                        $delivery->is_sync_rakuten = 1; //乐天物流信息是否同步 (0:未同步，1:已同步)
                        $delivery->save();
                    }

                    $logData[] = $orderNo; //日志数据
                    RakutenLogs::logs(RakutenLogs::$customerOrderLogistics, date('Y-m-d H:i:s', time()).',['. 1 .']条,订单物流同步成功!', $logData);
                }
            }

            sleep(1);
        }

        /*
        //客户订单发货明细
        $deliveryDetailList = CustomerDeliveryDetail::query()
            ->where('plat_id', SysPlat::PLAT_RAKUTEN) //乐天平台
            ->where('status', '<=', 5) //发货状态
            ->where('sync_status', CustomerDeliveryDetail::SYNC_STATUS_YES) //1：平台物流已同步
            ->where('is_sync_rakuten', 0)  //0：乐天物流未同步
            ->where('created_at', '>=', '2024-11-01 00:00:00')
            ->get();
        if (!$deliveryDetailList) die('not data!!!');

        //rakuten乐天物流公司
        $rakutenCompany = ExpressCompany::options(['platform_type' => SysPlat::PLAT_RAKUTEN], 'name_en', 'code')->toArray();
        if (!$rakutenCompany) die('not logistics!!!');

        $i = 0;
        $logData = [];
        foreach ($deliveryDetailList as $key => $delivery) {

            $orderNo = $delivery->order_no;
            //乐天订单下的发货包裹id
            $basketId = RakutenOrderItem::query()->where('order_id',$orderNo)->value('basket_id');
            if (!$basketId) continue;

            $params = [];
            $basketidModelList = [];
            if ($delivery->shipping_detail_id) $params['shippingDetailId'] = $delivery->shipping_detail_id; //乐天发货明细id
            if ($delivery->tracking_no) $params['shippingNumber'] = $delivery->tracking_no; //乐天物流公司追踪号
            //乐天物流公司编码
            if ($delivery->delivery_company) {
                $params['deliveryCompany'] = $delivery->delivery_company;
            }else{
                $params['deliveryCompany'] = self::getRakutenCompanyCode($rakutenCompany, $delivery->logistics_type);
            }
            //乐天物流公司发货日期
            if ($delivery->delivered_at){
                $params['shippingDate'] = date('Y-m-d', strtotime($delivery->delivered_at));
            }else{
                $params['shippingDate'] = date('Y-m-d', time());
            }
            $basketidModelList[$key]['basketId'] = $basketId;
            $basketidModelList[$key]['ShippingModelList'][] = $params;

            $apiUrl = self::ORDER_UPDATE_ORDER_SHIPPING; //api方法(订单发货)
            $apiParams = [
                'orderNumber' => $orderNo,
                'BasketidModelList' => $basketidModelList
            ];

            //执行第一条（请求一次）
            if($key == 0){
                $result = RakutenClient::getRequest($apiUrl, $apiParams);
                if ($result) {
                    if ($result->MessageModelList) {
                        foreach ($result->MessageModelList as $k => $v){
                            //回写物流信息
                            $delivery->delivery_company = $params['deliveryCompany']; //rakuten物流公司编码
                            $delivery->shipping_date = $params['shippingDate']; //rakuten物流配送时间
                            $delivery->shipping_detail_id = $v->shippingDetailId; //rakuten物流发货明细id
                            $delivery->is_sync_rakuten = 1; //乐天物流信息是否同步 (0:未同步，1:已同步)
                            $delivery->save();

                            $logData[] = $orderNo; //日志数据
                        }

                        $i++;
                    }
                }
                RakutenLogs::logs(RakutenLogs::$customerOrderLogistics, date('Y-m-d H:i:s', time()).',['. $i .']条,订单物流同步成功!', $logData);
            }
        }*/

    }

    /**
     * 获取乐天物流公司对应的物流编码
     * @param $rakutenCompany
     * @param $logistics_type
     * @return int|string
     */
    public static function getRakutenCompanyCode($rakutenCompany, $logistics_type){
        $deliveryCompanyCode = 1000; //其他 （其他：1000（默认的物流公司编码））
        if ($rakutenCompany && $logistics_type) {
            foreach ($rakutenCompany as $code => $name){
                $amazonLogisticsStr = mb_substr($logistics_type, 0, 3); //截取前3位，亚马逊平台下的物流公司名称
                $rakutenLogisticsStr = mb_substr($name, 0, 3);  //截取前3位，乐天平台下的物流公司名称
                if ($amazonLogisticsStr == $rakutenLogisticsStr) {
                    $deliveryCompanyCode = $code;
                }
            }
        }
        return $deliveryCompanyCode;
    }

    /**
     * （向rakuten平台回写库存数据）
     * 同步乐天库存
     */
    public static function syncRakutenInventory(){

        $platId = SysPlat::PLAT_RAKUTEN; //日本乐天平台
        $countryId = SysCountry::JP_COUNTRY_ID; //日本国家ID

        $rakutenSku = ProductRakutenSku::query()
            ->where('status',ProductRakutenSku::STATUS_YES) //启用
            ->get();
        if(!$rakutenSku) dd('finish');

        $sku = [];
        foreach ($rakutenSku as $key => $val){
            $sku[$key]['manageNumber'] = $val->manage_number;
            $sku[$key]['variantId'] = $val->variant_id;
            $sku[$key]['mode'] = 'ABSOLUTE';

            $inventroy = 0;

            //(单独渠道库存)
            if ($val->is_mix_inventory == ProductRakutenSku::IS_MIX_NO) {
                //海外仓代发
                if ($val->is_os_warehouse == ProductRakutenSku::OS_WAREHOUSE_YES) {
                    $dropshipping = DropshippingInventoryFnsku::getInstantAndTransit([],$val->psku_id,$platId); //海外代发库存（JP平台）
                    $inventroy = intval($dropshipping->instant) ?? 0;
                }

                //FBA
                if ($val->is_os_warehouse == ProductRakutenSku::OS_WAREHOUSE_NO) {
                    $fba = FBAMYIInventory::getInventoryFind($countryId, $val->psku_id); //FBA库存（JP国家）
                    $inventroy = intval($fba->instant) ?? 0;
                }
            }

            //(混合渠道库存)(fba+海外仓)
            if ($val->is_mix_inventory == ProductRakutenSku::IS_MIX_YES) {
                $fba = FBAMYIInventory::getInventoryFind($countryId, $val->psku_id); //FBA库存（JP国家）
                $dropshipping = DropshippingInventoryFnsku::getInstantAndTransit([],$val->psku_id,$platId); //海外代发库存（JP平台）

                $fbaInstant = intval($fba->instant) ?? 0;
                $dropshippingInstant = intval($dropshipping->instant) ?? 0;

                $inventroy = $fbaInstant + $dropshippingInstant;
            }

            $sku[$key]['quantity'] = $inventroy;
        }

        $apiParams['inventories'] = $sku;
        $apiUrl = self::INVENTORY_BULK_UPSERT; //api方法

        $res = RakutenClient::getRequest($apiUrl, $apiParams);
        dd($res);
    }

    /**
     * @param array $orderId
     * @return false
     */
    public static function getRakutenOrderBack($orderId = []){

        /*$orderId = [
            '407083-20241107-0211401938',
            '407083-20241107-0355001870',
            '407083-20241107-0390102011',
            '407083-20241107-0465701907',
            '407083-20241107-0471101991',
            '407083-20241107-0470402021',
            '407083-20241107-0592401852',
            '407083-20241108-0548202036',
            '407083-20241108-0669201834',
            '407083-20241108-0642001972',
            '407083-20241108-0664502085',

            '407083-20241107-0423701967',
            '407083-20241107-0578501831',
            '407083-20241107-0339502082',
            '407083-20241108-0709202009',
            '407083-20241108-0827001972',
            '407083-20241108-0837601942',
            '407083-20241108-0855701886',
            '407083-20241108-0998201844'
        ];*/

        //dd('rakuten-API!');
        if (!$orderId) return false;

        //创建rakuten订单及明细
        $apiUrlOne = self::ORDER_GET_ORDER; //api方法
        $apiParamsOne['version'] = 7;
        $apiParamsOne['orderNumberList'] = $orderId;
        $rakutenOrders = RakutenClient::getRequest($apiUrlOne, $apiParamsOne);

        if ($rakutenOrders) {
            DB::connection('mysql_rakuten')->beginTransaction();
            try {
                if ($rakutenOrders->OrderModelList) {
                    foreach ($rakutenOrders->OrderModelList as $item) {
                        $orderNo = $item->orderNumber;
                        $rakutenOrder = RakutenOrder::query()->where('order_id', $orderNo)->first();
                        if ($rakutenOrder) continue;

                        //订单
                        $order = [];
                        $order['order_id'] = $orderNo;
                        $order['order_progress'] = $item->orderProgress;
                        $order['order_datetime'] = strtotime($item->orderDatetime);
                        $order['order_type'] = $item->orderType;
                        $order['goods_price'] = $item->goodsPrice ?? 0;
                        $order['total_price'] = $item->totalPrice ?? 0; //订单总金额
                        $order['total_coupon_price'] = $item->couponAllTotalPrice ?? 0; //订单总优惠金额
                        $order['total_point_price'] = $item->PointModel->usedPoint ?? 0; //订单总优惠积分
                        $order['request_price'] = $item->requestPrice ?? 0; //订单实际总金额

                        $orderItem = []; //订单明细
                        $orderAddress = []; //订单地址
                        $orderShipping = []; //订单物流(初始包裹id)
                        $orderShippingDetails = []; //订单物流明细(初始包裹id)
                        foreach ($item->PackageModelList as $key => $value) {

                            //订单物流
                            $basketId = $value->basketId;
                            $orderShipping[$key]['basket_id'] = $basketId;

                            //物流明细
                            $orderShippingDetail = [];
                            if($value->ShippingModelList){
                                foreach ($value->ShippingModelList as $k1 => $v1) {
                                    $orderShippingDetail[$k1]['order_id'] = $orderNo;
                                    $orderShippingDetail[$k1]['shipping_detail_id'] = $v1->shippingDetailId ?? '';
                                    $orderShippingDetail[$k1]['shipping_number'] = $v1->shippingNumber ?? '';
                                    $orderShippingDetail[$k1]['delivery_company'] = $v1->deliveryCompany ?? '';
                                    $orderShippingDetail[$k1]['delivery_company_name'] = $v1->deliveryCompanyName ?? '';
                                    $orderShippingDetail[$k1]['shipping_date'] = $v1->shippingDate ?? '';
                                }
                            }else{
                                $orderShippingDetail[0]['order_id'] = $orderNo;
                            }
                            $orderShippingDetails[$basketId] = $orderShippingDetail;

                            //订单明细
                            if ($value->ItemModelList) {
                                foreach ($value->ItemModelList as $k2 => $v2) {
                                    $orderItem[$k2]['item_id'] = $v2->itemId;
                                    $orderItem[$k2]['basket_id'] = $basketId;
                                    $orderItem[$k2]['item_detail_id'] = $v2->itemDetailId;
                                    $orderItem[$k2]['item_name'] = $v2->itemName ?? '';
                                    $orderItem[$k2]['manage_number'] = $v2->manageNumber ?? '';
                                    $orderItem[$k2]['item_number'] = $v2->itemNumber ?? '';
                                    if ($v2->SkuModelList) {
                                        foreach ($v2->SkuModelList as $skuList => $sku){
                                            $pskuId = ProductSku::getValueByCode(trim($sku->variantId), 'id');
                                            $orderItem[$k2]['psku_id'] = $pskuId ?? 0; //erp公司产品ID
                                            $orderItem[$k2]['variant_id'] = trim($sku->variantId) ?? ''; //乐天产品变体ID
                                            $orderItem[$k2]['platform_sku'] = $sku->merchantDefinedSkuId ?? ''; //乐天平台sku
                                        }
                                        $orderItem[$k2]['platform_sku_info'] = json_encode($v2->SkuModelList, JSON_UNESCAPED_UNICODE) ?? ''; //乐天平台sku信息
                                    }
                                    $orderItem[$k2]['units'] = $v2->units ?? 0;
                                    $orderItem[$k2]['price'] = $v2->price ?? 0;
                                }
                            }

                            //订单地址
                            if ($value->SenderModel) {
                                //包裹收件人地址
                                $orderAddress['country'] = 'JP';
                                $orderAddress['country_code'] = 'JP';
                                $orderAddress['family_name'] = $value->SenderModel->familyName . $value->SenderModel->firstName ?? '';
                                $orderAddress['prefecture'] = $value->SenderModel->prefecture ?? '';
                                $orderAddress['city'] = $value->SenderModel->city ?? '';
                                $orderAddress['address'] = $value->SenderModel->subAddress ?? '';
                                $orderAddress['zip_code'] = $value->SenderModel->zipCode1 . $value->SenderModel->zipCode2 ?? '';
                                $orderAddress['email'] = $item->OrdererModel->emailAddress ?? ''; //订购人邮箱
                                $orderAddress['phone_number'] = $value->SenderModel->phoneNumber1 . $value->SenderModel->phoneNumber2 . $value->SenderModel->phoneNumber3 ?? '';
                            }
                        }

                        //创建rakuten订单
                        $rakutenOrder = RakutenOrder::query()->create($order);
                        $rakutenOrder->rakuten_orders_items()->createMany($orderItem);
                        $rakutenOrder->rakuten_orders_address()->create($orderAddress);

                        ////物流
                        //$orderShippingObj = $rakutenOrder->rakuten_orders_shipping()->createMany($orderShipping);
                        //if ($orderShippingObj) {
                        //    foreach ($orderShippingObj as $shipping){
                        //        $shipping->rakuten_orders_shipping_details()->createMany($orderShippingDetails[$shipping->basket_id]);
                        //    }
                        //}
                    }

                    DB::connection('mysql_rakuten')->commit();
                }
            }catch (\Exception $e){
                DB::connection('mysql_rakuten')->rollBack();
                report($e);
            }
        }
    }
}
